﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace VkSample82
{
    public class MoonSystem : ComponentSystem
    {
        private readonly ILogger<MoonSystem> _Logger;
        private float moonAngle;
        private readonly Vector3 Y = new Vector3(0, 1, 0);

        public MoonSystem(ILogger<MoonSystem> logger)
        {
            _Logger = logger;
        }

        public override void Initialization()
        {
            ContextManager.Foreach<MoonGroup>((group) =>
            {
                group.Transform.Position = new Vector3(180, 0, 0);
                Context context = ContextManager.GetContext(group.Entity);
                ref MVPMatrix mvp = ref context.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateTranslation(180, 0, 0);
                return group;
            });
        }

        public override void Update(TimeSpan lastStamp)
        {
            try
            {
                moonAngle += 0.4f;
                if (moonAngle >= 360) moonAngle = 0;
                ContextManager.Foreach<MoonGroup>((group) =>
                {
                    Context context = ContextManager.GetContext(group.Entity);
                    ref MVPMatrix mvp = ref context.GetMVPMatrix();
                    mvp.ModelMatrix = Matrix4x4.CreateTranslation(group.Transform.Position) * Matrix4x4.CreateFromAxisAngle(Y, moonAngle * MathF.PI / 180.0f);
                    context.PushToRenderGroup();
                });
            }
            catch (Exception e)
            {
                _Logger.LogInformation(e.Message);
            }
        }
    }

    struct MoonGroup
    {
        public Entity Entity;
        public MoonComponent Moon;
        public TransformComponent Transform;
    }
}
